package com.ztgf.commodity.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ztgf.commodity.common.config.YmlConfig;
import com.ztgf.commodity.mapper.CommodityFilterAttributesMapper;
import com.ztgf.commodity.models.bo.AttributesQueryBO;
import com.ztgf.commodity.models.bo.CommodityFilterAttributesNewBO;
import com.ztgf.commodity.models.dto.CommodityFilterAttributesDTO;
import com.ztgf.commodity.models.service.ICommodityFilterAttributesService;
import com.ztgf.commodity.models.vo.CommodityFilterAttributesNewVO;
import com.ztgf.commodity.models.vo.CommodityFilterOneVO;
import com.ztgf.common.constant.Result;
import com.ztgf.common.enums.CodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static com.ztgf.common.utils.UtilConstants.*;

/*
 * @author: chenyu.wang
 * @date: 2020-09-04
 * @description:
 */
@Slf4j
@DubboService
public class CommodityFilterAttributesServiceImpl extends ServiceImpl<CommodityFilterAttributesMapper, CommodityFilterAttributesDTO> implements ICommodityFilterAttributesService {

    @Resource
    private YmlConfig ymlConfig;

    /*
     * @description:后台管理系统筛选属性列表
     * @author: chenyu.wang
     * @date: 2020-09-04
     */
    @Override
    public Page<CommodityFilterAttributesNewVO> queryPageList(AttributesQueryBO bo) {
        Page<CommodityFilterAttributesNewVO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        List<CommodityFilterAttributesNewVO> list = baseMapper.queryListPage(page, bo);
        page.setRecords(list);
        return page;
    }

    /*
     * @description:根据id获取筛选属性
     * @author: chenyu.wang
     * @date: 2020-09-04
     */
    @Override
    public CommodityFilterAttributesNewVO queryById(Long id) {
        return baseMapper.queryById(id);
    }

    /*
     * @description:添加筛选属性
     * @author: chenyu.wang
     * @date: 2020-09-08
     */
    @Override
    public Result<List<String>> add(String object) {
        Result<List<String>> result = new Result<>();
        Long id = ymlConfig.getPkId();
        //父级
        CommodityFilterAttributesNewBO vo = JSONObject.parseObject(object, CommodityFilterAttributesNewBO.class);
        //子集
        List<CommodityFilterAttributesNewBO> childList = JSONObject.parseArray(vo.getChildList(), CommodityFilterAttributesNewBO.class);
        //保存父级
        CommodityFilterAttributesDTO attributesDTO = new CommodityFilterAttributesDTO();
        attributesDTO.setName(vo.getFilterName());
        attributesDTO.setStatus(0);
        attributesDTO.setIsPublish(1);
        attributesDTO.setSort(vo.getSort());
        attributesDTO.setParentId((long) ZERO);
        attributesDTO.setId(id);
        attributesDTO.setNotes(vo.getNotes());
        boolean insert = this.insert(attributesDTO);
        if (!insert) {
            result.setCode(CodeEnum.FAIL_100007.getCode());
            result.setMsg(CodeEnum.FAIL_100007.getMsg());
            return result;
        }
        if (isNull(childList)) {
            result.setCode(CodeEnum.SUCCESS.getCode());
            result.setMsg(CodeEnum.SUCCESS.getMsg());
            return result;
        }
        List<CommodityFilterAttributesDTO> addList = new ArrayList<>();
        for (CommodityFilterAttributesNewBO newBO : childList) {
            CommodityFilterAttributesDTO dto = new CommodityFilterAttributesDTO();
            dto.setName(newBO.getFilterName());
            dto.setStatus(ZERO);
            dto.setIsPublish(ONE);
            dto.setSort(newBO.getSort());
            dto.setParentId(id);
            dto.setId(ymlConfig.getPkId());
            addList.add(dto);
        }
        boolean insertBatch = this.insertBatch(addList);
        if (insertBatch) {
            result.setCode(CodeEnum.SUCCESS.getCode());
            result.setMsg(CodeEnum.SUCCESS.getMsg());
            return result;
        } else {
            result.setCode(CodeEnum.FAIL_100007.getCode());
            result.setMsg(CodeEnum.FAIL_100007.getMsg());
            return result;
        }
    }

    /*
     * @description:修改筛选属性
     * @author: chenyu.wang
     * @date: 2020-09-08
     */
    @Transactional
    @Override
    public Result<List<String>> updateById(String object) {
        Result<List<String>> result = new Result<>();
        //父级
        CommodityFilterAttributesNewBO vo = JSONObject.parseObject(object, CommodityFilterAttributesNewBO.class);
        //子集
        List<CommodityFilterAttributesNewBO> childList = JSONObject.parseArray(vo.getChildList(), CommodityFilterAttributesNewBO.class);
        //保存父级
        CommodityFilterAttributesDTO attributesDTO = new CommodityFilterAttributesDTO();
        attributesDTO.setName(vo.getFilterName());
        attributesDTO.setStatus(0);
        attributesDTO.setIsPublish(1);
        attributesDTO.setSort(vo.getSort());
        attributesDTO.setId(vo.getId());
        attributesDTO.setNotes(vo.getNotes());
        boolean updateById = this.updateById(attributesDTO);
        if (!updateById) {
            result.setCode(CodeEnum.FAIL_100008.getCode());
            result.setMsg(CodeEnum.FAIL_100008.getMsg());
            return result;
        }
        if (isNull(childList)) {
            result.setCode(CodeEnum.SUCCESS.getCode());
            result.setMsg(CodeEnum.SUCCESS.getMsg());
            return result;
        }
        CommodityFilterAttributesDTO filterAttributesDTO;
        for (CommodityFilterAttributesNewBO commodityFilterAttributesNewBO : childList) {
            filterAttributesDTO = new CommodityFilterAttributesDTO();
            if (null == commodityFilterAttributesNewBO.getId()) {
                filterAttributesDTO.setName(commodityFilterAttributesNewBO.getFilterName());
                filterAttributesDTO.setStatus(ZERO);
                filterAttributesDTO.setIsPublish(ONE);
                filterAttributesDTO.setSort(commodityFilterAttributesNewBO.getSort());
                filterAttributesDTO.setParentId(vo.getId());
                filterAttributesDTO.setId(ymlConfig.getPkId());
                this.insert(filterAttributesDTO);
            } else {
                filterAttributesDTO.setName(commodityFilterAttributesNewBO.getFilterName());
                filterAttributesDTO.setSort(commodityFilterAttributesNewBO.getSort());
                filterAttributesDTO.setNotes(commodityFilterAttributesNewBO.getNotes());
                filterAttributesDTO.setId(commodityFilterAttributesNewBO.getId());
                this.updateById(filterAttributesDTO);
            }
        }
        result.setCode(CodeEnum.SUCCESS.getCode());
        result.setMsg(CodeEnum.SUCCESS.getMsg());
        return result;
    }

    /*
     * @description:后台管理系统筛选属性列表,用于类目新增、修改
     * @author: chenyu.wang
     * @date: 2020-09-08
     */
    @Override
    public List<CommodityFilterAttributesDTO> queryList() {
        Wrapper<CommodityFilterAttributesDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("status", ZERO);
        wrapper.eq("is_publish", ONE);
        wrapper.eq("parent_id", ZERO);
        return this.selectList(wrapper);
    }

    /*
     * @description:根据分类查询筛选属性
     * @author: chenyu.wang
     * @date: 2020-09-08
     */
    @Override
    public List<CommodityFilterAttributesNewVO> queryByCategoryId(Long categoryId, String filterName) {
        return baseMapper.queryByCategoryId(categoryId, filterName);
    }

    /*
     * @description:获取筛选属性树形结构，用于商品查看详情
     * @author: chenyu.wang
     * @date: 2020-09-08
     */
    @Override
    public List<CommodityFilterOneVO> creatTree(String ids) {
        List<CommodityFilterOneVO> realTopList = new ArrayList<>();
        List<CommodityFilterOneVO> realNextList = new ArrayList<>();
        List<CommodityFilterOneVO> realList = new ArrayList<>();
        //查询顶级
        Wrapper<CommodityFilterAttributesDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("status", ZERO);
        wrapper.eq("is_publish", ONE);
        wrapper.eq("parent_id", ZERO);
        List<CommodityFilterAttributesDTO> topList = this.selectList(wrapper);
        if (!isNull(topList)) {
            for (CommodityFilterAttributesDTO topDto : topList) {
                CommodityFilterOneVO filterOneVO = new CommodityFilterOneVO();
                filterOneVO.setId(topDto.getId());
                filterOneVO.setParentId(topDto.getParentId());
                filterOneVO.setFilterName(topDto.getName());
                realTopList.add(filterOneVO);
            }
        }
        //获取下级
        String[] split = ids.split(",");
        for (String id : split) {
            CommodityFilterAttributesDTO nextDTO = this.selectById(id);
            if (nextDTO != null) {
                CommodityFilterOneVO nextVO = new CommodityFilterOneVO();
                nextVO.setId(nextDTO.getId());
                nextVO.setParentId(nextDTO.getParentId());
                nextVO.setFilterName(nextDTO.getName());
                realNextList.add(nextVO);
            }
        }
        realList.addAll(realTopList);
        realList.addAll(realNextList);
        return this.builTree(realList);
    }

    /*
     * @description:根据父级id查询筛选属性子集
     * @author: chenyu.wang
     * @date: 2020-09-08
     */
    @Override
    public List<CommodityFilterOneVO> getByParentId(Long id) {
        List<CommodityFilterOneVO> list = new ArrayList<>();
        Wrapper<CommodityFilterAttributesDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("status", ZERO);
        wrapper.eq("is_publish", ONE);
        wrapper.eq("parent_id", id);
        List<CommodityFilterAttributesDTO> attributesDTOS = this.selectList(wrapper);
        if (isNull(attributesDTOS)) {
            return null;
        }
        for (CommodityFilterAttributesDTO attributesDTO : attributesDTOS) {
            CommodityFilterOneVO vo = new CommodityFilterOneVO();
            vo.setId(attributesDTO.getId());
            vo.setParentId(attributesDTO.getParentId());
            vo.setFilterName(attributesDTO.getName());
            list.add(vo);
        }
        return list;
    }

    @Override
    public Page<CommodityFilterAttributesNewVO> newQueryPageList(AttributesQueryBO bo) {
        Page<CommodityFilterAttributesNewVO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        List<CommodityFilterAttributesNewVO> list = baseMapper.queryListPage(page, bo);
        if (!isNull(list)) {
            page.setRecords(list);
            return page;
        }
        Page<CommodityFilterAttributesDTO> attrPage = new Page<>(bo.getPageNo(), bo.getPageSize());
        Wrapper<CommodityFilterAttributesDTO> wrapper = new EntityWrapper<>();
        wrapper.like("name", bo.getAttributesName());
        List<CommodityFilterAttributesDTO> attrList = this.selectPage(attrPage, wrapper).getRecords();
        if (isNull(attrList)) {
            return null;
        }
        List<String> ids = new ArrayList<>();
        for (CommodityFilterAttributesDTO dto : attrList) {
            if (dto.getParentId() == 0) {
                ids.add(dto.getId().toString());
            } else {
                if (ids.contains(dto.getParentId().toString())) {
                    continue;
                } else {
                    ids.add(dto.getParentId().toString());
                }
            }
        }
        if (isNull(ids)) {
            return null;
        }
        List<CommodityFilterAttributesNewVO> realList = new ArrayList<>();
        for (String id : ids) {
            CommodityFilterAttributesDTO dto = this.selectById(id);
            if (null != dto) {
                List<CommodityFilterAttributesNewVO> childList = baseMapper.queryByParentId(dto.getId());
                CommodityFilterAttributesNewVO newVO = new CommodityFilterAttributesNewVO();
                newVO.setId(dto.getId());
                newVO.setFilterName(dto.getName());
                newVO.setState(dto.getStatus());
                newVO.setIsPublish(dto.getIsPublish());
                newVO.setSort(dto.getSort());
                newVO.setParentId(dto.getParentId());
                newVO.setNotes(dto.getNotes());
                if (!isNull(childList)) {
                    newVO.setChildList(childList);
                }
                realList.add(newVO);
            }
        }
        page.setRecords(realList);
        return page;
    }

    //建立树形结构
    public List<CommodityFilterOneVO> builTree(List<CommodityFilterOneVO> menuList) {
        List<CommodityFilterOneVO> treeMenus = new ArrayList<>();
        for (CommodityFilterOneVO menuNode : getRootNode(menuList)) {
            menuNode = this.buildChilTree(menuNode, menuList);
            treeMenus.add(menuNode);
        }
        return treeMenus;
    }

    //递归，建立子树形结构
    private CommodityFilterOneVO buildChilTree(CommodityFilterOneVO pNode, List<CommodityFilterOneVO> menuList) {
        List<CommodityFilterOneVO> chilMenus = new ArrayList<>();
        for (CommodityFilterOneVO menuNode : menuList) {
            if (menuNode.getParentId().equals(pNode.getId())) {
                chilMenus.add(this.buildChilTree(menuNode, menuList));
            }
        }
        pNode.setChildList(chilMenus);
        return pNode;
    }

    //获取根节点
    private List<CommodityFilterOneVO> getRootNode(List<CommodityFilterOneVO> menuList) {
        List<CommodityFilterOneVO> rootMenuLists = new ArrayList<>();
        for (CommodityFilterOneVO menuNode : menuList) {
            if (menuNode.getParentId().intValue() == 0) {
                rootMenuLists.add(menuNode);
            }
        }
        return rootMenuLists;
    }


}
